package com.cheyun.netsalev3.utils;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;

import com.cheyun.netsalev3.tencenttim.utils.DemoLog;


public class MyAudioPlayer {

    private static final String TAG = MyAudioPlayer.class.getSimpleName();
    private static MyAudioPlayer sInstance = new MyAudioPlayer();

    private MediaPlayer mPlayer;
    private Callback mPlayCallback;
    public static MyAudioPlayer getInstance() {
        return sInstance;
    }

    public void startPlay(AssetFileDescriptor fileDescriptor , Callback callback) {
        mPlayCallback = callback;
        try {
            mPlayer = new MediaPlayer();
            mPlayer.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getLength());
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
//                    stopInternalPlay();
//                    onPlayCompleted(true);
                    mp.start();
                }
            });
            mPlayer.prepare();
            mPlayer.start();
        } catch (Exception e) {
            DemoLog.w(TAG, e.getMessage());
            stopInternalPlay();
            onPlayCompleted(false);
        }
    }

    public void stopPlay() {
        stopInternalPlay();
        onPlayCompleted(false);
        mPlayCallback = null;
    }

    private void stopInternalPlay() {
        if (mPlayer == null) {
            return;
        }
        mPlayer.release();
        mPlayer = null;
    }

    public boolean isPlaying() {
        if (mPlayer != null && mPlayer.isPlaying()) {
            return true;
        }
        return false;
    }

    private void onPlayCompleted(boolean success) {
        if (mPlayCallback != null) {
            mPlayCallback.onCompletion(success);
        }
        mPlayer = null;
    }

    public interface Callback {
        void onCompletion(Boolean success);
    }
}
